package com.lg.erp.controller.zhangkai;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lg.erp.entity.JsonResult;
import com.lg.erp.entity.SCompany;
import com.lg.erp.entity.SUser;
import com.lg.erp.entity.ligen.Supplier;
import com.lg.erp.entity.zhangkai.Customer;
import com.lg.erp.entity.zhangkai.Par;
import com.lg.erp.entity.zhangkai.Relation;
import com.lg.erp.service.ISCompanyService;
import com.lg.erp.service.IUserService;
import com.lg.erp.service.ligen.ISupplierService;
import com.lg.erp.service.zhangkai.ICustomerService;
import com.lg.erp.service.zhangkai.IRelationService;
import com.lg.erp.service.zhangkai.ParService;
import org.apache.commons.net.ntp.TimeStamp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.*;

import javax.management.relation.RelationService;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class ParController {
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private ParService parService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ISCompanyService companyService;
    @Autowired
    private IRelationService relationService;
    @Autowired
    private ISupplierService supplierService;

    private static SCompany sCompany;

    //申请
    @RequestMapping(value = "/par",method = RequestMethod.POST)
    public JsonResult addPar(@RequestBody Par par){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(principal instanceof User) {
            User user = (User) principal;
            SUser one = userService.getOne(new QueryWrapper<SUser>().lambda().eq(SUser::getUsername, user.getUsername()));
            sCompany=companyService.getById(one.getCompanyId());
        }
        //设置默认的申请状态1
        par.settParStatus("已申请");
        //设置申请时间
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        par.settParTime(format);
        par.settParComA(sCompany.getId());
        parService.save(par);
        return new JsonResult(1,"ok",null);
    }
    //分页查询
    @RequestMapping(value = "/pars",method = RequestMethod.GET)
    public JsonResult findPage(@RequestParam(value = "curr",required = false,defaultValue = "1")Long curr,@RequestParam(value = "size",required = false,defaultValue = "5")Integer size){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(principal instanceof User) {
            User user = (User) principal;
            SUser one = userService.getOne(new QueryWrapper<SUser>().lambda().eq(SUser::getUsername, user.getUsername()));
            sCompany=companyService.getById(one.getCompanyId());
        }
        Page<Par> parPage = new Page<>(curr, size);
        IPage<Par> page = parService.page(parPage, new QueryWrapper<Par>().lambda().eq(Par::gettParComB,sCompany.getId()));
        List<Par> records = page.getRecords();
        //查询单个公司
        records.forEach(par -> {
                par.setCompany(companyService.getById(par.gettParComA()));
        });
        return new JsonResult(1,"ok",page);
    }
    //按照时间查询
    @RequestMapping(value = "/par/conditionQuery/{date1}/{date2}",method = RequestMethod.GET)
    public JsonResult conditionQuery(@PathVariable("date1")Date date1,@PathVariable("date2")Date date2){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(date1);
        String format1 = simpleDateFormat.format(date2);
        List<Par> pars = parService.conditionQuery(format, format1,sCompany.getId());
        pars.forEach(par -> {
            par.setCompany(companyService.getById(par.gettParComA()));
        });
        return new JsonResult(1,"ok",pars);
    }
    //更新审核状态
    @RequestMapping(value = "/par",method = RequestMethod.PUT)
    public JsonResult modifyStatus(@RequestBody Par par){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Relation relation = new Relation();
        //审核通过
        if (par.gettParStatus2().equals("通过")){
            //成为客户
            if (par.gettParRel().equals("0")){
                //查找是否重复
                Relation one = relationService.getOne(new QueryWrapper<Relation>().lambda().eq(Relation::getCustomerId, par.getCompany().getId()).eq(Relation::getSupplierId, sCompany.getId()));
                if (one!=null){
                    relationService.remove(new QueryWrapper<Relation>().lambda().eq(Relation::getCustomerId, par.getCompany().getId()).eq(Relation::getSupplierId, sCompany.getId()));
                }
                relation.setCustomerId(par.getCompany().getId());
                relation.setSupplierId(sCompany.getId());
                relationService.save(relation);
                //添加到customer表中
                Customer customer = new Customer();
                customer.setAddress(par.getCompany().getCompanyProvince()+par.getCompany().getCompanyCity()+par.getCompany().getCompanyArea());
                customer.setBusiness(par.getCompany().getBusinessScope());
                customer.setName(par.getCompany().getCompanyName());
                customer.setTelephone(par.getCompany().getFixedTel());
                customer.setEmail(par.getCompany().getCompanyEmail());
                customer.setRemark(par.getCompany().getRremark());
                Timestamp ts = new Timestamp(new Date().getTime());
                customer.setCreateTime(ts);
                customer.setId(UUID.randomUUID().toString().replace("-","").substring(0,5));
                customerService.save(customer);

                //添加到supplier
                Supplier supplier = new Supplier();
                supplier.setAddress(sCompany.getCompanyProvince()+sCompany.getCompanyCity()+sCompany.getCompanyArea());
                supplier.setBusiness(sCompany.getBusinessScope());
                supplier.setName(sCompany.getCompanyName());
                supplier.setTelephone(sCompany.getFixedTel());
                supplier.setEmail(sCompany.getCompanyEmail());
                LocalDateTime now = LocalDateTime.now();
                supplier.setCreateTime(now);
                supplier.setId(UUID.randomUUID().toString().replace("-","").substring(0,5));
                supplierService.save(supplier);
            }
            //成为供应商
            else {
                Relation one = relationService.getOne(new QueryWrapper<Relation>().lambda().eq(Relation::getCustomerId, sCompany.getId()).eq(Relation::getSupplierId, par.getCompany().getId()));
                if (one!=null){
                    relationService.remove(new QueryWrapper<Relation>().lambda().eq(Relation::getCustomerId, sCompany.getId()).eq(Relation::getSupplierId, par.getCompany().getId()));
                }
                relation.setSupplierId(par.getCompany().getId());
                relation.setCustomerId(sCompany.getId());
                relationService.save(relation);
                Supplier supplier = new Supplier();
                supplier.setAddress(par.getCompany().getCompanyProvince()+par.getCompany().getCompanyCity()+par.getCompany().getCompanyArea());
                supplier.setBusiness(par.getCompany().getBusinessScope());
                supplier.setName(par.getCompany().getCompanyName());
                supplier.setTelephone(par.getCompany().getFixedTel());
                supplier.setEmail(par.getCompany().getCompanyEmail());
                LocalDateTime now = LocalDateTime.now();
                supplier.setCreateTime(now);
                supplier.setId(UUID.randomUUID().toString().replace("-","").substring(0,5));
                supplierService.save(supplier);

                Customer customer = new Customer();
                customer.setAddress(sCompany.getCompanyProvince()+sCompany.getCompanyCity()+sCompany.getCompanyArea());
                customer.setBusiness(sCompany.getBusinessScope());
                customer.setName(sCompany.getCompanyName());
                customer.setTelephone(sCompany.getFixedTel());
                customer.setEmail(sCompany.getCompanyEmail());
                customer.setRemark(sCompany.getRremark());
                Timestamp ts = new Timestamp(new Date().getTime());
                customer.setCreateTime(ts);
                customer.setId(UUID.randomUUID().toString().replace("-","").substring(0,5));
                customerService.save(customer);
            }
        }
        parService.updateById(par);
        return new JsonResult(1,"ok",null);
    }

    //删除par
    @RequestMapping(value = "/par/{id}",method = RequestMethod.DELETE)
    public JsonResult delete(@PathVariable("id")String id){
        parService.removeById(id);
        return new JsonResult(1,"ok",null);
    }
}
